import { ActionFunctionArgs, LoaderFunctionArgs, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData } from "@remix-run/react";
import { useTranslation } from "react-i18next";
import { authenticator, AuthenticatorResponse } from "~/.server/authentication";
import { PermissionModel } from "~/.server/models/permission";
import { FormFieldError } from "~/components/form_validate";
import { commitSession, getSession, themeSessionResolver } from "~/sessions.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { getTheme } = await themeSessionResolver(request)
  return {
    theme: getTheme(),
  }
}

export default function Login() {
  const { t } = useTranslation();
  const loaderData = useLoaderData<typeof loader>();
  const theme = loaderData.theme;
  let style = {
    background: "radial-gradient(ellipse at 50% 50%, hsl(263.4, 70%, 96%) 0%, hsl(0,0%,100%) 100%)"
  }
  if (theme && theme === "dark") {
    style = {
      background: "radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))"
    }
  }
  const actionData = useActionData<typeof action>();

  return (
    <div className="w-screen h-screen flex justify-center items-center" style={style}>
      <div className="sm:w-96 card bg-base-100 shadow-xl w-full h-auto">
        <div className="card-body">
          <div className="card-title">
            <h3>Login</h3>
            <span>Welcome back !</span>
          </div>
          <div className="card-body">
            <Form method="post">
              <label className="form-control w-full mt-4">
                <div className="label">
                  <span className="label-text after:content-['*'] after:ml-0.5 after:text-error">{t("username")}</span>
                </div>
                <input type="text"
                  name="username"
                  placeholder={t("username")}
                  className={`input input-bordered w-full ${actionData?.username && "input-error"}`} />
                <FormFieldError msg={actionData?.username} />
              </label>
              <label className="form-control w-full mt-4">
                <div className="label">
                  <span className="label-text after:content-['*'] after:ml-0.5 after:text-error">{t("username")}</span>
                </div>
                <input type="password"
                  name="password"
                  placeholder={t("password")}
                  className={`input input-bordered w-full ${actionData?.password && "input-error"}`} />
                <FormFieldError msg={actionData?.password} />
              </label>

              <div className="flex justify-between items-center mt-4">
                <div className="flex items-center">
                  <label className="cursor-pointer label gap-1">
                    <input
                      type="checkbox"
                      className="checkbox checkbox-primary"
                      name="rememberMe"
                    />
                    <span className="label-text">{t("remember_me")}</span>
                  </label>
                </div>
                {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
                <a href="#" className="link link-hover text-sm text-primary">忘记密码？</a>
              </div>
              <button className=" btn btn-primary w-full mt-6">登录</button>
              {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
              <a href="#" className="link link-hover block text-center text-sm text-primary mt-4">没有账号？注册</a>
            </Form>
          </div>
        </div>
      </div>
    </div>
  )
}

export const action = async ({
  request,
}: ActionFunctionArgs) => {
  const data = await authenticator.authenticate("user-pass", request) as AuthenticatorResponse;
  if (data.code != 0) {
    return data.error;
  }
  const session = await getSession(request.headers.get("Cookie"));
  const user = {
    id: data.user?.id,
    username: data.user?.username,
    nickname: data.user?.nickname,
    avatar: data.user?.avatar,
    permissionPaths: undefined,
    permissions: undefined,
  }
  session.set("user", user);
  session.set("permissionPaths", data.user?.permissionPaths);
  const reducePermission = (permission: PermissionModel): PermissionModel => {
    return {
      id: permission.id,
      name: permission.name,
      zh_name: permission.zh_name,
      path: permission.path,
      icon: permission.icon,
      children: permission.children?.map(child => reducePermission(child)),
    }
  };
  const permissions: PermissionModel[] = [];
  data.user?.permissions?.sort((a, b) => (a.sort || 0) - (b.sort || 0)).map(permission => {
    permissions.push(reducePermission(permission));
  });
  session.set("permissions", permissions);
  return redirect("/admin", {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });
}